
function basePath(){
    var curWwwPath = window.document.location.href;
    var pathName =  window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0,pos);
    var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return (localhostPath + projectName);
}

loading();

var page = 1;
var page_item_num = 0;
var item_num = 10;

$(function () {
    getCourses(page);
    validatorU();
    validatorA();
    $("#add_course_btn").click(function () {
        addCourse();
    });
    $("#update_course_btn").click(function () {
        updateCourse();
    });

});


function validatorU() {
    $('#updateForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            newCourseName: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '课程名不能为空'
                    },
                    different: {
                        field: 'name',
                        message: '该课程名已存在，请重新输入'
                    }
                }
            }
        }
    });
}

function validatorA() {
    $('#addForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            courseName1: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '课程名不能为空'
                    },
                    different: {
                        field: 'name',
                        message: '该课程名已存在，请重新输入'
                    }
                }
            },

        }
    });
}

function getCourse() {

    var url = basePath()+"/course/toupdate_course.do";
    var data = {"courseId": courseId};
    $.get(url, data, function (data) {
        if (data.status == 0) {
            $("#coursename1").val(data.data.name);
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");
}

function getCourses(pageNum) {
    $.ajax({
        url: basePath()+'/edu/course/all_course.do',
        type: 'GET',
        async: 'true',
        data: {
            "pageNum": pageNum,
            "pageSize": item_num
        },
        dataType: 'json',
        success: function (data) {
            removeLoading();
            var pageResult = data.data;
            var item = data.data.list;
            page_item_num = item.length;
            page = setPage(pageResult.pageNum, pageResult.pages, "getCourses");
            if (data.success) {
                if (data.data.list == "") {
                    $('#table').hide();
                    $('#pagination').hide();
                    $('#after_div').after("<div class='alert alert-warning alert-dismissible' role='alert'>\n" +
                        "  <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>\n" +
                        "  <strong style='padding-left: 30px;'>暂时没有任何课程</strong>" +
                        "</div>");
                } else {
                    $('.alert').remove();
                    $('#table').show();
                    $('#pagination').show();
                    $("#result").html("");
                    for (var i = 0; i < item.length; i++) {
                        var temp = $("#m_template").clone();
                        temp.attr("id", item[i].id);
                        temp.removeAttr("style");
                        temp.find(".c_num").html(pageResult.pageSize * (pageResult.pageNum - 1) + 1 + i);
                        temp.find(".c_name").html(item[i].name);
                        //修改按钮组装
                        var ucontent = "<button type='button'  class='btn btn-primary btn-xs btn-warning'  style='margin-right: 10px;' onclick='toUpdate(" + item[i].id + ");' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                        //删除按钮组装
                        var dcontent = "<button type='button'  class='btn btn-primary btn-xs btn-danger'  onclick='deleteCourse(" + item[i].id + ");' ><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></span><span style='margin: 0px 8px;'>删除</span></button>"
                        temp.find(".c_update").html(ucontent);
                        temp.find(".c_operate").html(dcontent);
                        $("#result").append(temp);
                    }
                }
            }
        }
    })
}

function deleteCourse(courseId) {

    bootbox.setDefaults('locale', 'zh_CN');
    bootbox.confirm("确认删除?", function (res) {
        if (res) {
            var url = basePath()+"/edu/course/delete_course.do";
            var data = {"courseId": courseId};
            $.get(url, data, function (data) {
                if (data.status == 0) {
                    bootbox.alert("删除成功");
                    if (page_item_num == '1') {
                        getCourses(page - 1);
                    } else {
                        getCourses(page);
                    }

                } else {
                    bootbox.alert(data.msg);
                }
            }, "JSON");
        }
    });
}
;

function toUpdate(courseId) {
    var url = basePath()+"/edu/course/toupdate_course.do";
    var data = {"courseId": courseId};
    $.get(url, data, function (data) {
        if (data.status == 0) {
            $("#newCourseName").val(data.data.name);
            $("#newCourseNameId").val(courseId);
            $("#changCourse").modal("show");
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");

}

function updateCourse() {

    // 提交前先主动验证表单
    var bv = $("#updateForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }
    var url = basePath()+"/edu/course/update_course.do";
    var name = $("#newCourseName").val();
    var id = $("#newCourseNameId").val();
    var data = {"id": id, "name": name};
    $.post(url, data, function (data) {
        if (data.status == 0) {
            $("#changCourse").modal("hide");
            getCourses(page);
            bootbox.alert(data.msg);
        } else {
            $('#updateForm').data('bootstrapValidator').updateStatus('newCourseName', 'INVALID', 'different')
        }
    }, "JSON");
}
;

function addCourse() {
    // 提交前先主动验证表单
    var bv = $("#addForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    var coursename = $("#courseName1").val();
    $("#courseName1").val("");

    $.ajax({
        url: basePath()+"/edu/course/add_course.do",
        type: "post",
        async: "true",
        data: {"name": coursename},
        dataType: "json",
        success: function (data) {
            if (data.status == 0) {
                clearAddModel();
                bootbox.alert("添加成功");
                if (page_item_num == item_num) {
                    getCourses(page + 1);
                } else {
                    getCourses(page);
                }
            }
            else {
                $('#addForm').data('bootstrapValidator').updateStatus('courseName1', 'INVALID', 'different')
            }
        }
    });

}

function clearUpdateModel() {
    $('#changCourse').modal('hide');
    $('#newCourseName').val("");

    $('#updateForm').data('bootstrapValidator').destroy();
    $('#updateForm').data('bootstrapValidator', null);
    $("form[id='updateForm'] > div").addClass('has-success');
    validatorU();
}

function clearAddModel() {
    $('#addCourse').modal('hide');
    $('#courseName1').val("");

    $('#addForm').data('bootstrapValidator').destroy();
    $('#addForm').data('bootstrapValidator', null);
    $("form[id='addForm'] > div").addClass('has-success');
    validatorA();
}